<template>
  <div>
    <van-search
      v-model.trim="value"
      shape="round"
      placeholder="请输入搜索关键词"
      @input="onInput"
    />

    <!-- 热门搜索 -->
    <div v-if="searchList ? !searchList.length :false">
      <p>热门搜索</p>
      <div>
        <span @click="searchRes(item.first)" v-for="item in hotSongList" :key="item.first" class="desc">{{ item.first }}</span>
      </div>
    </div>

     <!-- 最佳匹配 -->
    <div v-else>
      <p>最佳匹配</p>

      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
         <MusicList v-for="(item,index) in searchList" :key="index" :name="item.name" :song="item.al.name + ' - ' +item.name"></MusicList>
      </van-list>
    </div>
  </div>
</template>

<script>
import { hotSongList, getSongList } from '@/Api/search.js'
import MusicList from '@/components/Newsong'
export default {
  data () {
    return {
      value: '',
      hotSongList: [],
      searchList: [],
      list: [],
      loading: false,
      finished: false,
      page: 1
    }
  },
  components: {
    MusicList
  },
  created () {
    this.getHotList()
  },

  methods: {
    async getHotList () {
      const res = await hotSongList()
      this.hotSongList = res.data.result.hots
    },
    async searchRes (val) {
      this.value = val
      const res = await getSongList({
        keywords: this.value,
        limit: 10
      })
      this.searchList = res.data.result.songs
    },
    async onInput () {
      this.page = 1
      if (this.time) clearTimeout(this.time)
      if (this.value === '') {
        this.searchList = []
        return
      }
      this.time = setTimeout(async () => {
        const res = await getSongList({
          keywords: this.value,
          limit: 10
        })
        this.searchList = res.data.result.songs
      }, 700)
    },
    async onLoad () {
      this.page++
      const res = await getSongList({
        keywords: this.value,
        limit: 10,
        offset: (this.page - 1) * 10
      })
      if (res.data.result.songs) {
        this.searchList.push(...res.data.result.songs)
        this.loading = false
      } else {
        this.finished = true
      }
    }
  }
}
</script>

<style scoped>
.desc{
  display: inline-block;
  border: 1px solid gray;
  border-radius: 15px;
  padding: 5px 8px;
  margin: 5px 0;
  margin-right: 5px;
}
</style>
